package bookmanagementsystem.gui;

import bookmanagementsystem.dao.UserDAO;
import bookmanagementsystem.model.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ModifyPersonalInfoFrame extends JFrame {
    private JTextField genderField;
    private JTextField phoneNumberField;
    private JTextField emailField;
    private JButton saveButton;

    private UserDAO userDAO;
    private String currentUserID;

    public ModifyPersonalInfoFrame(String currentUserID) {
        this.currentUserID = currentUserID;
        userDAO = new UserDAO();

        setTitle("修改个人信息");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        initComponents();
        addComponentsToFrame();
        addActionListeners();
    }

    private void initComponents() {
        genderField = new JTextField(20);
        phoneNumberField = new JTextField(20);
        emailField = new JTextField(20);
        saveButton = new JButton("保存修改");
    }

    private void addComponentsToFrame() {
        JPanel panel = new JPanel(new GridLayout(4, 2));

        panel.add(new JLabel("性别："));
        panel.add(genderField);
        panel.add(new JLabel("电话号码："));
        panel.add(phoneNumberField);
        panel.add(new JLabel("邮箱："));
        panel.add(emailField);
        panel.add(saveButton);

        getContentPane().add(panel);
    }

    private void addActionListeners() {
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String gender = genderField.getText();
                String phoneNumber = phoneNumberField.getText();
                String email = emailField.getText();

                User currentUser = userDAO.getUserById(currentUserID);
                if (currentUser == null) {
                    JOptionPane.showMessageDialog(ModifyPersonalInfoFrame.this, "获取当前用户信息失败，请联系管理员。");
                    return;
                }

                currentUser.setGender(gender);
                currentUser.setPhoneNumber(phoneNumber);
                currentUser.setEmail(email);

                if (userDAO.updateUserInfo(currentUser)) {
                    JOptionPane.showMessageDialog(ModifyPersonalInfoFrame.this, "个人信息修改成功！");
                    dispose(); // 关闭当前修改信息窗口
                } else {
                    JOptionPane.showMessageDialog(ModifyPersonalInfoFrame.this, "个人信息修改失败，请联系管理员。");
                }
            }
        });
    }
}